//
//  PlayerManger.m
//  SBPlayer
//
//  Created by 黄锋 on 15/8/17.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PlayerManger.h"
#import "MBProgressHUD.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface PlayerManger () <NSURLConnectionDataDelegate>

@property(nonatomic, strong) MBProgressHUD *hud;
@property(nonatomic) CGRect rect;
@property(nonatomic) NSInteger index;

@property(nonatomic, strong) UIButton *playButton;
@property(nonatomic, strong) UISlider *slider;
@property(nonatomic, strong) UILabel *currentTime;
@property(nonatomic, strong) UILabel *totalTime;

@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic) CGFloat beginTime;

@property(nonatomic, strong) NSMutableDictionary *dic;

@end

@implementation PlayerManger

+ (instancetype)defaultManger
{
    static PlayerManger *m = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        m = [[PlayerManger alloc] init];
    });
    return m;
}

- (instancetype)init
{
    if (self = [super init]) {
        [self addNotification];
    }
    return self;
}

- (void)playWithURL:(NSString *)url frame:(CGRect)rect mediaType:(MediaType)mediaType
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(available) name:MPMovieDurationAvailableNotification object:self];
    [_timer invalidate];
    
    [_songView removeFromSuperview];
    [self.view removeFromSuperview];

    if (_startBlock) {
        _startBlock();
    }
    _mediaType = mediaType;
    _index++;
    _beginTime = 0;
    self.contentURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    _rect = rect;
    if (_mediaType == Song) {
        self.view.frame = CGRectZero;
        _songView = [[UIView alloc] initWithFrame:rect];
        _songView.backgroundColor = [UIColor clearColor];
        [_songView addSubview:self.view];
        [self creatPlayButtonWithHud];
    } else if (_mediaType == Vedio) {
        self.view.frame = rect;
        self.view.backgroundColor = [UIColor clearColor];
        self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight  | UIViewAutoresizingFlexibleWidth;
        self.controlStyle = MPMovieControlStyleEmbedded;
        self.scalingMode = MPMovieScalingModeAspectFit;
        self.initialPlaybackTime = -1.0;
        if (url) {
            [self creatHud];
        }
    }
}

- (void)creatSongView
{
    _playButton.selected = YES;
    [UIView animateWithDuration:.5 animations:^{
        _playButton.frame = CGRectMake(0, 0, 46, 46);
        _playButton.transform = CGAffineTransformRotate(_playButton.transform, M_PI);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:.5 animations:^{
            _playButton.transform = CGAffineTransformRotate(_playButton.transform, M_PI);
        }];
        if (!_slider) {
            _slider = [[UISlider alloc] initWithFrame:CGRectMake(45, 18, _rect.size.width - 50, 10)];
            [_slider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
            _slider.minimumTrackTintColor = [UIColor redColor];
            [_slider addTarget:self action:@selector(setTimeTo:) forControlEvents:UIControlEventValueChanged];
        }
        _slider.value = 0;
        [_songView addSubview:_slider];
        if (!_currentTime) {
            _currentTime = [[UILabel alloc] initWithFrame:CGRectMake(47, _rect.size.height - 15, 30, 13)];
            _currentTime.textColor = [UIColor whiteColor];
            _currentTime.adjustsFontSizeToFitWidth = YES;
        }
        _currentTime.text = @"";
        [_songView addSubview:_currentTime];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeCurrentTime) userInfo:nil repeats:YES];
        if (!_totalTime) {
            _totalTime = [[UILabel alloc] initWithFrame:CGRectMake(_rect.size.width - 35, _rect.size.height - 15, 30, 13)];
            _totalTime.textColor = [UIColor whiteColor];
            _totalTime.adjustsFontSizeToFitWidth = YES;
        }
        _totalTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)self.duration / 60, (NSInteger)self.duration % 60];
        [_songView addSubview:_totalTime];
    });
}

- (void)changeCurrentTime
{
    NSArray *events = self.accessLog.events;
    MPMovieAccessLogEvent *currentEvent = [events lastObject];
    CGFloat time = _beginTime + currentEvent.durationWatched;
    _currentTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)time / 60, (NSInteger)time % 60];
    if (self.duration) {
        _slider.value = time / self.duration;
        CGFloat leftTime = self.duration - time;
        _totalTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)leftTime / 60, (NSInteger)leftTime % 60];
    }
}

- (void)playOrPause:(UIButton *)sender
{
    if (sender.selected) {
        [self pause];
    } else {
        [self play];
    }
    sender.selected = !sender.selected;
}

- (void)setTimeTo:(UISlider *)sender
{
    _beginTime = self.duration * (double)(sender.value / sender.maximumValue);
    if (self.playbackState == MPMoviePlaybackStatePlaying) {
        [self pause];
    }
    [self setCurrentPlaybackTime:_beginTime];
    _playButton.selected = YES;
    [self play];
}

- (void)creatPlayButtonWithHud
{
    if (!_playButton) {
        self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _playButton.frame = CGRectMake(_rect.size.width / 2 - 23, 0, 46, 46);
        [_playButton setImage:[UIImage imageNamed:@"iconfont-bofang-1"] forState:UIControlStateNormal];
        [_playButton setImage:[UIImage imageNamed:@"iconfont-icon12"] forState:UIControlStateSelected];
        [_playButton addTarget:self action:@selector(playOrPause:) forControlEvents:UIControlEventTouchUpInside];
        _playButton.selected = NO;
        _playButton.layer.masksToBounds = YES;
        _playButton.layer.cornerRadius = 23;
    }
    _playButton.frame = CGRectMake(_rect.size.width / 2 - 23, 0, 46, 46);
    [_songView addSubview:_playButton];
    [self creatHud];
}

- (void)creatHud
{
    if (_mediaType == Vedio) {
        _hud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:_hud];
    } else {
        _hud = [[MBProgressHUD alloc] initWithView:_playButton];
        [_playButton addSubview:_hud];
    }
    [_hud show:YES];
    NSInteger index = _index;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (index == _index) {
            if (self.playbackState == MPMoviePlaybackStateStopped) {
                [_hud removeFromSuperview];
                [_hud show:NO];
                [self.view removeFromSuperview];
                if (_mediaType == Song) {
                    [_timer invalidate];
                    [_songView removeFromSuperview];
                    if (_finishBlock) {
                        _finishBlock();
                    }
                }
            }
        }
    });
}

- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerPlaybackDidFinish) name:MPMoviePlayerPlaybackDidFinishNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(available) name:MPMovieDurationAvailableNotification object:self];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)change:(NSNotification *)notification
{
    if (_mediaType == Vedio) {
        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        if (orientation == UIInterfaceOrientationLandscapeRight  || orientation ==UIInterfaceOrientationLandscapeLeft) {
            [self setFullscreen:YES animated:YES];
            self.view.frame = [UIScreen mainScreen].bounds;
        } else if (orientation == UIInterfaceOrientationPortrait  || orientation == UIInterfaceOrientationPortraitUpsideDown) {
            [self setFullscreen:NO animated:NO];
            self.view.frame = _rect;
        }
    }
}

- (void)playerPlaybackDidFinish
{
//    NSLog(@"playerPlaybackDidFinish");
    if (_mediaType == Vedio) {
        [self setFullscreen:NO animated:NO];
        [self.view removeFromSuperview];
    } else {
        [_timer invalidate];
        [_songView removeFromSuperview];
    }
    if (_finishBlock) {
        _finishBlock();
    }
}

- (void)available
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieDurationAvailableNotification object:self];
//    NSLog(@"******************************************");
    [_hud removeFromSuperview];
    [_hud show:NO];
    if (_mediaType == Vedio) {
        self.backgroundView.backgroundColor = [UIColor blackColor];
    } else if (_mediaType == Song) {
        [self creatSongView];
    }
    [self play];
}

#pragma mark - 下载视频

- (NSMutableDictionary *)dic
{
    if (!_dic) {
        _dic = [NSMutableDictionary dictionary];
    }
    return _dic;
}

- (void)loadWithUrl:(NSString *)urlStr
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
//        NSLog(@"无访问相册权限");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"无访问相册权限" object:nil userInfo:nil];
        return;
    }
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    for (NSURL *aa in _dic) {
        if ([aa isEqual:url]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"已添加到下载列表" object:nil userInfo:nil];
//            NSLog(@"已添加到下载列表");
            return;
        }
    }
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[@"temp." stringByAppendingString:[(__bridge NSString *)(contextInfo) pathExtension]]];
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    [_dic removeObjectForKey:[NSURL URLWithString:(__bridge NSString *)(contextInfo)]];
    if (!error) {
//        NSLog(@"保存成功");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"保存成功" object:nil userInfo:@{@"信息":@"文件已保存至相册"}];
    } else {
//        NSLog(@"保存失败");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SavingError" object:nil userInfo:nil];
    }
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//    NSLog(@"下载失败");
    [_dic removeObjectForKey:connection.currentRequest.URL];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"下载失败" object:nil userInfo:@{@"信息":@"文件下载失败"}];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//    NSLog(@"开始下载");
    NSMutableData *data = [NSMutableData data];
    [self.dic setObject:data forKey:connection.currentRequest.URL];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"didReceiveResponse" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"开始下载" object:nil userInfo:@{@"信息":@"正在下载文件"}];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSMutableData *data1 = _dic[connection.currentRequest.URL];
    [data1 appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//    NSLog(@"下载成功");
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[@"temp." stringByAppendingString:[connection.currentRequest.URL.absoluteString pathExtension]]];
    NSMutableData *data = _dic[connection.currentRequest.URL];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [data writeToFile:path atomically:YES];
        UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), (__bridge void *)connection.currentRequest.URL.absoluteString);
    });
}

#pragma mark - 保存图片

- (void)saveImageWithUrl:(NSString *)urlStr
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
//        NSLog(@"无访问相册权限");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"无访问相册权限" object:nil userInfo:nil];
        return;
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]], self, @selector(image: didFinishSavingWithError: contextInfo:), nil);
    });
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"保存成功" object:nil userInfo:@{@"信息":@"图片已保存至相册"}];
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"保存失败" object:nil userInfo:nil];
    }
}

@end
